import os

def create_file(path, content):
    """创建文件并写入内容"""
    os.makedirs(os.path.dirname(path), exist_ok=True)
    with open(path, 'w', encoding='utf-8') as f:
        f.write(content)

def create_voice_alarm_app():
    # 项目根目录
    base_dir = "VoiceAlarmApp"

    # Java包目录
    java_dir = os.path.join(base_dir, "src", "main", "java", "com", "example", "voicealarm")

    # 资源目录
    res_dir = os.path.join(base_dir, "src", "main", "res")
    layout_dir = os.path.join(res_dir, "layout")
    values_dir = os.path.join(res_dir, "values")
    drawable_dir = os.path.join(res_dir, "drawable")

    # 创建目录
    os.makedirs(java_dir, exist_ok=True)
    os.makedirs(layout_dir, exist_ok=True)
    os.makedirs(values_dir, exist_ok=True)
    os.makedirs(drawable_dir, exist_ok=True)

    # 创建Java文件
    java_files = {
        "Alarm.java": """
package com.example.voicealarm;

import java.io.Serializable;
import java.util.Calendar;

public class Alarm implements Serializable {
    private int id;
    private int hour;
    private int minute;
    private String message;
    private int playCount;
    private boolean[] repeatDays; // 周日到周六
    private boolean enabled;

    public Alarm(int hour, int minute, String message, int playCount, boolean[] repeatDays) {
        this.hour = hour;
        this.minute = minute;
        this.message = message;
        this.playCount = playCount;
        this.repeatDays = repeatDays;
        this.enabled = true;
    }

    // Getters and setters
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }
    public int getHour() { return hour; }
    public void setHour(int hour) { this.hour = hour; }
    public int getMinute() { return minute; }
    public void setMinute(int minute) { this.minute = minute; }
    public String getMessage() { return message; }
    public void setMessage(String message) { this.message = message; }
    public int getPlayCount() { return playCount; }
    public void setPlayCount(int playCount) { this.playCount = playCount; }
    public boolean[] getRepeatDays() { return repeatDays; }
    public void setRepeatDays(boolean[] repeatDays) { this.repeatDays = repeatDays; }
    public boolean isEnabled() { return enabled; }
    public void setEnabled(boolean enabled) { this.enabled = enabled; }

    public String getFormattedTime() {
        return String.format("%02d:%02d", hour, minute);
    }

    public Calendar getNextAlarmTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minute);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        // 如果当前时间已经过了闹钟时间，设置为明天
        if (calendar.getTimeInMillis() <= System.currentTimeMillis()) {
            calendar.add(Calendar.DAY_OF_YEAR, 1);
        }
        return calendar;
    }

    public boolean isRepeating() {
        for (boolean day : repeatDays) {
            if (day) return true;
        }
        return false;
    }
}
""",

        "AlarmDatabaseHelper.java": """
package com.example.voicealarm;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

public class AlarmDatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "alarms.db";
    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_ALARMS = "alarms";

    // 列名
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_HOUR = "hour";
    private static final String COLUMN_MINUTE = "minute";
    private static final String COLUMN_MESSAGE = "message";
    private static final String COLUMN_PLAY_COUNT = "play_count";
    private static final String COLUMN_SUN = "sun";
    private static final String COLUMN_MON = "mon";
    private static final String COLUMN_TUE = "tue";
    private static final String COLUMN_WED = "wed";
    private static final String COLUMN_THU = "thu";
    private static final String COLUMN_FRI = "fri";
    private static final String COLUMN_SAT = "sat";
    private static final String COLUMN_ENABLED = "enabled";

    public AlarmDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_ALARMS_TABLE = "CREATE TABLE " + TABLE_ALARMS + "("
                + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                + COLUMN_HOUR + " INTEGER,"
                + COLUMN_MINUTE + " INTEGER,"
                + COLUMN_MESSAGE + " TEXT,"
                + COLUMN_PLAY_COUNT + " INTEGER,"
                + COLUMN_SUN + " INTEGER,"
                + COLUMN_MON + " INTEGER,"
                + COLUMN_TUE + " INTEGER,"
                + COLUMN_WED + " INTEGER,"
                + COLUMN_THU + " INTEGER,"
                + COLUMN_FRI + " INTEGER,"
                + COLUMN_SAT + " INTEGER,"
                + COLUMN_ENABLED + " INTEGER"
                + ")";
        db.execSQL(CREATE_ALARMS_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_ALARMS);
        onCreate(db);
    }

    public void addAlarm(Alarm alarm) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_HOUR, alarm.getHour());
        values.put(COLUMN_MINUTE, alarm.getMinute());
        values.put(COLUMN_MESSAGE, alarm.getMessage());
        values.put(COLUMN_PLAY_COUNT, alarm.getPlayCount());

        boolean[] repeatDays = alarm.getRepeatDays();
        values.put(COLUMN_SUN, repeatDays[0] ? 1 : 0);
        values.put(COLUMN_MON, repeatDays[1] ? 1 : 0);
        values.put(COLUMN_TUE, repeatDays[2] ? 1 : 0);
        values.put(COLUMN_WED, repeatDays[3] ? 1 : 0);
        values.put(COLUMN_THU, repeatDays[4] ? 1 : 0);
        values.put(COLUMN_FRI, repeatDays[5] ? 1 : 0);
        values.put(COLUMN_SAT, repeatDays[6] ? 1 : 0);
        values.put(COLUMN_ENABLED, alarm.isEnabled() ? 1 : 0);

        long id = db.insert(TABLE_ALARMS, null, values);
        alarm.setId((int) id);
        db.close();
    }

    public List<Alarm> getAllAlarms() {
        List<Alarm> alarmList = new ArrayList<>();
        String selectQuery = "SELECT * FROM " + TABLE_ALARMS + " ORDER BY " + COLUMN_HOUR + ", " + COLUMN_MINUTE;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        if (cursor.moveToFirst()) {
            do {
                Alarm alarm = new Alarm(
                        cursor.getInt(1),
                        cursor.getInt(2),
                        cursor.getString(3),
                        cursor.getInt(4),
                        new boolean[]{
                                cursor.getInt(5) == 1,
                                cursor.getInt(6) == 1,
                                cursor.getInt(7) == 1,
                                cursor.getInt(8) == 1,
                                cursor.getInt(9) == 1,
                                cursor.getInt(10) == 1,
                                cursor.getInt(11) == 1
                        }
                );
                alarm.setId(cursor.getInt(0));
                alarm.setEnabled(cursor.getInt(12) == 1);
                alarmList.add(alarm);
            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();
        return alarmList;
    }

    public void updateAlarm(Alarm alarm) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_HOUR, alarm.getHour());
        values.put(COLUMN_MINUTE, alarm.getMinute());
        values.put(COLUMN_MESSAGE, alarm.getMessage());
        values.put(COLUMN_PLAY_COUNT, alarm.getPlayCount());

        boolean[] repeatDays = alarm.getRepeatDays();
        values.put(COLUMN_SUN, repeatDays[0] ? 1 : 0);
        values.put(COLUMN_MON, repeatDays[1] ? 1 : 0);
        values.put(COLUMN_TUE, repeatDays[2] ? 1 : 0);
        values.put(COLUMN_WED, repeatDays[3] ? 1 : 0);
        values.put(COLUMN_THU, repeatDays[4] ? 1 : 0);
        values.put(COLUMN_FRI, repeatDays[5] ? 1 : 0);
        values.put(COLUMN_SAT, repeatDays[6] ? 1 : 0);
        values.put(COLUMN_ENABLED, alarm.isEnabled() ? 1 : 0);

        db.update(TABLE_ALARMS, values, COLUMN_ID + " = ?", new String[]{String.valueOf(alarm.getId())});
        db.close();
    }

    public void deleteAlarm(int id) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_ALARMS, COLUMN_ID + " = ?", new String[]{String.valueOf(id)});
        db.close();
    }

    public Alarm getAlarmById(int id) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_ALARMS, null, COLUMN_ID + "=?", new String[]{String.valueOf(id)}, null, null, null);

        if (cursor != null && cursor.moveToFirst()) {
            Alarm alarm = new Alarm(
                cursor.getInt(1),
                cursor.getInt(2),
                cursor.getString(3),
                cursor.getInt(4),
                new boolean[]{
                    cursor.getInt(5) == 1,
                    cursor.getInt(6) == 1,
                    cursor.getInt(7) == 1,
                    cursor.getInt(8) == 1,
                    cursor.getInt(9) == 1,
                    cursor.getInt(10) == 1,
                    cursor.getInt(11) == 1
                }
            );
            alarm.setId(cursor.getInt(0));
            alarm.setEnabled(cursor.getInt(12) == 1);
            cursor.close();
            return alarm;
        }
        return null;
    }
}
""",

        "AlarmAdapter.java": """
package com.example.voicealarm;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.Switch;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class AlarmAdapter extends RecyclerView.Adapter<AlarmAdapter.AlarmViewHolder> {
    private List<Alarm> alarmList;
    private Context context;
    private OnAlarmListener onAlarmListener;

    public AlarmAdapter(Context context, List<Alarm> alarmList, OnAlarmListener onAlarmListener) {
        this.context = context;
        this.alarmList = alarmList;
        this.onAlarmListener = onAlarmListener;
    }

    @NonNull
    @Override
    public AlarmViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_alarm, parent, false);
        return new AlarmViewHolder(view, onAlarmListener);
    }

    @Override
    public void onBindViewHolder(@NonNull AlarmViewHolder holder, int position) {
        Alarm alarm = alarmList.get(position);
        holder.timeTextView.setText(alarm.getFormattedTime());
        holder.messageTextView.setText(alarm.getMessage());
        holder.playCountTextView.setText("播放次数: " + alarm.getPlayCount());
        holder.repeatTextView.setText(formatRepeatDays(alarm.getRepeatDays()));
        holder.enabledSwitch.setChecked(alarm.isEnabled());
    }

    @Override
    public int getItemCount() {
        return alarmList.size();
    }

    private String formatRepeatDays(boolean[] repeatDays) {
        String[] days = {"日", "一", "二", "三", "四", "五", "六"};
        StringBuilder sb = new StringBuilder("重复: ");
        boolean hasRepeat = false;

        for (int i = 0; i < repeatDays.length; i++) {
            if (repeatDays[i]) {
                sb.append(days[i]).append(" ");
                hasRepeat = true;
            }
        }

        if (!hasRepeat) {
            return "不重复";
        }
        return sb.toString();
    }

    public static class AlarmViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView timeTextView, messageTextView, playCountTextView, repeatTextView;
        Switch enabledSwitch;
        ImageButton editButton, deleteButton;
        OnAlarmListener onAlarmListener;

        public AlarmViewHolder(@NonNull View itemView, OnAlarmListener onAlarmListener) {
            super(itemView);
            timeTextView = itemView.findViewById(R.id.tv_time);
            messageTextView = itemView.findViewById(R.id.tv_message);
            playCountTextView = itemView.findViewById(R.id.tv_play_count);
            repeatTextView = itemView.findViewById(R.id.tv_repeat);
            enabledSwitch = itemView.findViewById(R.id.switch_enabled);
            editButton = itemView.findViewById(R.id.btn_edit);
            deleteButton = itemView.findViewById(R.id.btn_delete);
            this.onAlarmListener = onAlarmListener;

            itemView.setOnClickListener(this);
            editButton.setOnClickListener(this);
            deleteButton.setOnClickListener(this);

            enabledSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    onAlarmListener.onAlarmToggle(getAdapterPosition(), isChecked);
                }
            });
        }

        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.btn_edit) {
                onAlarmListener.onAlarmEdit(getAdapterPosition());
            } else if (v.getId() == R.id.btn_delete) {
                onAlarmListener.onAlarmDelete(getAdapterPosition());
            } else {
                onAlarmListener.onAlarmClick(getAdapterPosition());
            }
        }
    }

    public interface OnAlarmListener {
        void onAlarmClick(int position);
        void onAlarmEdit(int position);
        void onAlarmDelete(int position);
        void onAlarmToggle(int position, boolean isEnabled);
    }
}
""",

        "AlarmReceiver.java": """
package com.example.voicealarm;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        int alarmId = intent.getIntExtra("ALARM_ID", -1);
        if (alarmId != -1) {
            Intent alertIntent = new Intent(context, AlarmAlertActivity.class);
            alertIntent.putExtra("ALARM_ID", alarmId);
            alertIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(alertIntent);
        }
    }
}
""",

        "MainActivity.java": """
package com.example.voicealarm;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.List;

public class MainActivity extends AppCompatActivity implements AlarmAdapter.OnAlarmListener {
    private RecyclerView recyclerView;
    private AlarmAdapter alarmAdapter;
    private AlarmDatabaseHelper dbHelper;
    private List<Alarm> alarmList;
    private AlarmManager alarmManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        dbHelper = new AlarmDatabaseHelper(this);
        alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        loadAlarms();

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(v -> showAddAlarmDialog());
    }

    private void loadAlarms() {
        alarmList = dbHelper.getAllAlarms();
        alarmAdapter = new AlarmAdapter(this, alarmList, this);
        recyclerView.setAdapter(alarmAdapter);
    }

    private void showAddAlarmDialog() {
        AddAlarmDialog dialog = new AddAlarmDialog(this, new AddAlarmDialog.OnAlarmAddedListener() {
            @Override
            public void onAlarmAdded(Alarm alarm) {
                dbHelper.addAlarm(alarm);
                scheduleAlarm(alarm);
                loadAlarms();
            }
        });
        dialog.show();
    }

    private void scheduleAlarm(Alarm alarm) {
        if (!alarm.isEnabled()) return;

        Intent intent = new Intent(this, AlarmReceiver.class);
        intent.putExtra("ALARM_ID", alarm.getId());

        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                this, alarm.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

        Calendar calendar = alarm.getNextAlarmTime();

        if (alarm.isRepeating()) {
            // 设置重复闹钟
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                    calendar.getTimeInMillis(),
                    AlarmManager.INTERVAL_DAY * 7,
                    pendingIntent);
        } else {
            // 单次闹钟
            alarmManager.setExact(AlarmManager.RTC_WAKEUP,
                    calendar.getTimeInMillis(),
                    pendingIntent);
        }
    }

    private void cancelAlarm(Alarm alarm) {
        Intent intent = new Intent(this, AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                this, alarm.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
        alarmManager.cancel(pendingIntent);
    }

    @Override
    public void onAlarmClick(int position) {
        // 点击闹钟项
        Alarm alarm = alarmList.get(position);
        Toast.makeText(this, alarm.getMessage(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onAlarmEdit(int position) {
        // 编辑闹钟
        Alarm alarm = alarmList.get(position);
        AddAlarmDialog dialog = new AddAlarmDialog(this, alarm, new AddAlarmDialog.OnAlarmAddedListener() {
            @Override
            public void onAlarmAdded(Alarm updatedAlarm) {
                cancelAlarm(alarm);
                dbHelper.updateAlarm(updatedAlarm);
                scheduleAlarm(updatedAlarm);
                loadAlarms();
            }
        });
        dialog.show();
    }

    @Override
    public void onAlarmDelete(int position) {
        // 删除闹钟
        Alarm alarm = alarmList.get(position);
        cancelAlarm(alarm);
        dbHelper.deleteAlarm(alarm.getId());
        loadAlarms();
    }

    @Override
    public void onAlarmToggle(int position, boolean isEnabled) {
        // 切换闹钟开关
        Alarm alarm = alarmList.get(position);
        alarm.setEnabled(isEnabled);
        dbHelper.updateAlarm(alarm);

        if (isEnabled) {
            scheduleAlarm(alarm);
        } else {
            cancelAlarm(alarm);
        }
    }
}
""",

        "AlarmAlertActivity.java": """
package com.example.voicealarm;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.util.Locale;

public class AlarmAlertActivity extends AppCompatActivity {
    private TextToSpeech tts;
    private MediaPlayer mediaPlayer;
    private int alarmId;
    private Alarm alarm;
    private AlarmDatabaseHelper dbHelper;
    private int playCount = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm_alert);

        // 保持屏幕唤醒
        getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        alarmId = getIntent().getIntExtra("ALARM_ID", -1);
        if (alarmId == -1) {
            finish();
            return;
        }

        dbHelper = new AlarmDatabaseHelper(this);
        alarm = dbHelper.getAlarmById(alarmId);

        if (alarm == null) {
            finish();
            return;
        }

        TextView messageTextView = findViewById(R.id.tv_message);
        messageTextView.setText(alarm.getMessage());

        Button dismissButton = findViewById(R.id.btn_dismiss);
        Button snoozeButton = findViewById(R.id.btn_snooze);

        dismissButton.setOnClickListener(v -> {
            if (tts != null) {
                tts.stop();
                tts.shutdown();
            }
            if (mediaPlayer != null) {
                mediaPlayer.stop();
            }
            finish();
        });

        snoozeButton.setOnClickListener(v -> snoozeAlarm());

        // 初始化TTS
        tts = new TextToSpeech(this, status -> {
            if (status == TextToSpeech.SUCCESS) {
                int result = tts.setLanguage(Locale.CHINESE);
                if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                    // 如果语言不支持，使用默认提示音
                    playDefaultAlarmSound();
                } else {
                    speakAlarmMessage();
                }
            } else {
                playDefaultAlarmSound();
            }
        });
    }

    private void speakAlarmMessage() {
        if (playCount < alarm.getPlayCount()) {
            tts.speak(alarm.getMessage(), TextToSpeech.QUEUE_ADD, null, "alarm_" + playCount);
            playCount++;
        }
    }

    private void playDefaultAlarmSound() {
        mediaPlayer = MediaPlayer.create(this, R.raw.alarm_sound);
        mediaPlayer.setLooping(true);
        mediaPlayer.start();
    }

    private void snoozeAlarm() {
        // 设置10分钟后再次提醒
        if (tts != null) {
            tts.stop();
        }
        if (mediaPlayer != null) {
            mediaPlayer.stop();
        }

        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

        // 计算10分钟后时间
        long snoozeTime = System.currentTimeMillis() + 10 * 60 * 1000;

        Intent intent = new Intent(this, AlarmReceiver.class);
        intent.putExtra("ALARM_ID", alarmId);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                this, alarmId + 1000, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

        alarmManager.setExact(AlarmManager.RTC_WAKEUP, snoozeTime, pendingIntent);

        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
        }
    }
}
""",

        "AddAlarmDialog.java": """
package com.example.voicealarm;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.TimePicker;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;

import java.util.Objects;

public class AddAlarmDialog extends DialogFragment {
    private TimePicker timePicker;
    private EditText messageEditText;
    private NumberPicker playCountPicker;
    private CheckBox[] dayCheckBoxes;
    private OnAlarmAddedListener listener;
    private Alarm existingAlarm;

    public interface OnAlarmAddedListener {
        void onAlarmAdded(Alarm alarm);
    }

    public AddAlarmDialog() {}

    public AddAlarmDialog(OnAlarmAddedListener listener) {
        this.listener = listener;
    }

    public AddAlarmDialog(Alarm alarm, OnAlarmAddedListener listener) {
        this.existingAlarm = alarm;
        this.listener = listener;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
        LayoutInflater inflater = requireActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.dialog_add_alarm, null);

        timePicker = view.findViewById(R.id.timePicker);
        timePicker.setIs24HourView(true);

        messageEditText = view.findViewById(R.id.et_message);

        playCountPicker = view.findViewById(R.id.numberPicker);
        playCountPicker.setMinValue(1);
        playCountPicker.setMaxValue(5);
        playCountPicker.setValue(1);

        dayCheckBoxes = new CheckBox[]{
                view.findViewById(R.id.cb_sun),
                view.findViewById(R.id.cb_mon),
                view.findViewById(R.id.cb_tue),
                view.findViewById(R.id.cb_wed),
                view.findViewById(R.id.cb_thu),
                view.findViewById(R.id.cb_fri),
                view.findViewById(R.id.cb_sat)
        };

        Button saveButton = view.findViewById(R.id.btn_save);
        Button cancelButton = view.findViewById(R.id.btn_cancel);

        if (existingAlarm != null) {
            timePicker.setHour(existingAlarm.getHour());
            timePicker.setMinute(existingAlarm.getMinute());
            messageEditText.setText(existingAlarm.getMessage());
            playCountPicker.setValue(existingAlarm.getPlayCount());

            boolean[] repeatDays = existingAlarm.getRepeatDays();
            for (int i = 0; i < repeatDays.length; i++) {
                dayCheckBoxes[i].setChecked(repeatDays[i]);
            }
        }

        saveButton.setOnClickListener(v -> saveAlarm());
        cancelButton.setOnClickListener(v -> dismiss());

        builder.setView(view);
        return builder.create();
    }

    private void saveAlarm() {
        int hour = timePicker.getHour();
        int minute = timePicker.getMinute();
        String message = messageEditText.getText().toString().trim();
        int playCount = playCountPicker.getValue();

        if (message.isEmpty()) {
            message = "闹钟时间到了";
        }

        boolean[] repeatDays = new boolean[7];
        for (int i = 0; i < dayCheckBoxes.length; i++) {
            repeatDays[i] = dayCheckBoxes[i].isChecked();
        }

        Alarm alarm;
        if (existingAlarm != null) {
            alarm = existingAlarm;
            alarm.setHour(hour);
            alarm.setMinute(minute);
            alarm.setMessage(message);
            alarm.setPlayCount(playCount);
            alarm.setRepeatDays(repeatDays);
        } else {
            alarm = new Alarm(hour, minute, message, playCount, repeatDays);
        }

        if (listener != null) {
            listener.onAlarmAdded(alarm);
        }
        dismiss();
    }
}
"""
    }

    for file_name, content in java_files.items():
        create_file(os.path.join(java_dir, file_name), content)

    # 创建布局文件
    layout_files = {
        "activity_main.xml": """
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/background">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="8dp"
        android:clipToPadding="false"/>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="16dp"
        android:src="@drawable/ic_add"
        app:backgroundTint="@color/colorPrimary"
        app:tint="@android:color/white"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>
""",

        "item_alarm.xml": """
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="8dp"
    app:cardCornerRadius="8dp"
    app:cardElevation="4dp"
    android:background="@drawable/bg_card">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="16dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:gravity="center_vertical">

            <TextView
                android:id="@+id/tv_time"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:textSize="24sp"
                android:textStyle="bold"
                android:textColor="@color/textPrimary"/>

            <androidx.appcompat.widget.Switch
                android:id="@+id/switch_enabled"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
        </LinearLayout>

        <TextView
            android:id="@+id/tv_message"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:textSize="16sp"
            android:textColor="@color/textSecondary"/>

        <TextView
            android:id="@+id/tv_play_count"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="4dp"
            android:textSize="14sp"
            android:textColor="@color/textSecondary"/>

        <TextView
            android:id="@+id/tv_repeat"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="4dp"
            android:textSize="14sp"
            android:textColor="@color/textSecondary"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginTop="16dp">

            <ImageButton
                android:id="@+id/btn_edit"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:src="@drawable/ic_edit"
                android:background="?attr/selectableItemBackgroundBorderless"
                android:padding="8dp"/>

            <ImageButton
                android:id="@+id/btn_delete"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:src="@drawable/ic_delete"
                android:background="?attr/selectableItemBackgroundBorderless"
                android:padding="8dp"/>
        </LinearLayout>
    </LinearLayout>
</androidx.cardview.widget.CardView>
""",

        "activity_alarm_alert.xml": """
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:padding="32dp"
    android:background="@color/alarmBackground">

    <TextView
        android:id="@+id/tv_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:textColor="@android:color/black"
        android:text="闹钟时间到了"
        android:layout_marginBottom="32dp"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btn_dismiss"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="关闭"
            android:padding="16dp"
            android:textSize="18sp"
            android:background="@drawable/bg_button"
            android:textColor="@android:color/white"/>

        <Button
            android:id="@+id/btn_snooze"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="32dp"
            android:text="小睡"
            android:padding="16dp"
            android:textSize="18sp"
            android:background="@drawable/bg_button"
            android:textColor="@android:color/white"/>
    </LinearLayout>
</LinearLayout>
""",

        "dialog_add_alarm.xml": """
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="16dp">

    <TimePicker
        android:id="@+id/timePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"/>

    <EditText
        android:id="@+id/et_message"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:hint="闹钟提示语"
        android:inputType="text"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="16dp"
        android:gravity="center_vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="播放次数:"
            android:textSize="16sp"/>

        <NumberPicker
            android:id="@+id/numberPicker"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"/>
    </LinearLayout>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="重复"
        android:textSize="16sp"
        android:layout_marginTop="16dp"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="8dp">

        <CheckBox
            android:id="@+id/cb_sun"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="日"/>

        <CheckBox
            android:id="@+id/cb_mon"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="一"/>

        <CheckBox
            android:id="@+id/cb_tue"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="二"/>

        <CheckBox
            android:id="@+id/cb_wed"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="三"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="8dp">

        <CheckBox
            android:id="@+id/cb_thu"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="四"/>

        <CheckBox
            android:id="@+id/cb_fri"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="五"/>

        <CheckBox
            android:id="@+id/cb_sat"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="六"/>

        <View
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="24dp">

        <Button
            android:id="@+id/btn_cancel"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="取消"
            android:background="@drawable/bg_button"/>

        <Button
            android:id="@+id/btn_save"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginStart="16dp"
            android:text="保存"
            android:background="@drawable/bg_button"/>
    </LinearLayout>
</LinearLayout>
"""
    }

    for file_name, content in layout_files.items():
        create_file(os.path.join(layout_dir, file_name), content)

    # 创建资源文件
    res_files = {
        "values/colors.xml": """
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>

    <color name="background">#F5F5F5</color>
    <color name="alarmBackground">#FFF9C4</color>
    <color name="textPrimary">#212121</color>
    <color name="textSecondary">#757575</color>
</resources>
""",

        "values/strings.xml": """
<resources>
    <string name="app_name">语音闹钟</string>
    <string name="add_alarm">添加闹钟</string>
    <string name="alarm_message_hint">闹钟提示语</string>
    <string name="play_count">播放次数</string>
    <string name="repeat">重复</string>
    <string name="save">保存</string>
    <string name="cancel">取消</string>
    <string name="dismiss">关闭</string>
    <string name="snooze">小睡</string>
    <string name="no_repeat">不重复</string>
</resources>
""",

        # 简单矢量图标
        "drawable/ic_add.xml": """
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24">
    <path android:fillColor="#000000"
          android:pathData="M19,13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
</vector>
""",

        "drawable/ic_edit.xml": """
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24">
    <path android:fillColor="#000000"
          android:pathData="M3,17.25V21h3.75L17.81,9.94l-3.75,-3.75L3,17.25zM20.71,7.04c0.39,-0.39 0.39,-1.02 0,-1.41l-2.34,-2.34c-0.39,-0.39 -1.02,-0.39 -1.41,0l-1.83,1.83l3.75,3.75l1.83,-1.83z"/>
</vector>
""",

        "drawable/ic_delete.xml": """
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24">
    <path android:fillColor="#000000"
          android:pathData="M6,19c0,1.1 0.9,2 2,2h8c1.1,0 2,-0.9 2,-2V7H6V19zM19,4h-3.5l-1,-1h-5l-1,1H5v2h14V4z"/>
</vector>
""",

        "drawable/bg_card.xml": """
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@android:color/white"/>
    <corners android:radius="8dp"/>
</shape>
""",

        "drawable/bg_button.xml": """
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#3F51B5"/>
    <corners android:radius="8dp"/>
</shape>
""",

        # AndroidManifest.xml
        "AndroidManifest.xml": """
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.voicealarm">

    <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM"/>
    <uses-permission android:name="android.permission.USE_EXACT_ALARM"/>
    <uses-permission android:name="android.permission.VIBRATE"/>
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar">

        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".AlarmAlertActivity"
            android:theme="@style/Theme.AppCompat.Light.NoActionBar"
            android:screenOrientation="portrait"
            android:excludeFromRecents="true"/>

        <receiver android:name=".AlarmReceiver"/>
    </application>
</manifest>
"""
    }

    for file_name, content in res_files.items():
        path = os.path.join(base_dir, "src", "main", file_name)
        create_file(path, content)

if __name__ == "__main__":
    create_voice_alarm_app()
    print("语音闹钟应用创建完成！")